// pages/caseStudyTest/caseStudyTest.js
import CaseStudyTestApi from '../../api/caseStudyTest.js'
import {parseTime} from '../../utils/util'
import Dialog from '../../plugin/vant/dialog/dialog';

Page({

    /**
     * 页面的初始数据
     */
    data: {
        animationData:{},
        option: [
            {text: '不限', value: '0'},
            {text: '病史采集', value: '1'},
            {text: '体格检查', value: '2'},
            {text: '诊断', value: '3'},
        ],
        caseId: '0a5783c51c462fdae6f415a271c06fe3',
        caseData: {},
        operationLogList: [],//操作日志
        operationLogType: '0',//筛选type
        operationLogNumData: {
            bscjNum: 0,
            tgjcNum: 0,
            zdNumOne: 0,
            zdNumTwo: 0
        },
        bscjId:'',
        value1: 0,
        value: '',
        type: '1',//1.病史采集2.体格检查3.诊断
        toolShow: true, //菜单是否展开
        viewHeight: 0,
        bscjPlaceholder:'请输入关键词',
        bscjData: {
            addShow: false,
            focus:true,
            keyWord: '',
            keyWordList: [],
            resultList: []//查询结果数据
        },
        tgjcData: {
            keyWord: '',
            treeData: [],
            treeMenuIndex: 0,
            bodyStr: [],
            options: [],
            name: '',
            oneItem: {},
            radio: -1,
            resultFlag: false,
            showPoint:[],//听诊点

        },
        zdData: {
            keyWord: '',
            resultList: []//查询结果数据
        },
        interpretationModel: false,
        soundModel:false
    },

    /**
     * 生命周期函数--监听页面加载
     */
    onLoad: function (options) {
        const id = options.id
        this.setData({
            caseId: id
        })
        this.queryCaseDetailById()
        this.queryCaseBodyCheck()
        wx.enableAlertBeforeUnload({
            message: "是否结束练习？",
            success: function (res) {
                let _this = this
                if(_this.data.operationLogList.length > 0){
                    _this.endCaseTest()
                }
            },
            fail: function (errMsg) {
                console.log("方法注册失败：", errMsg);
            },
        });
    },

    /**
     * 生命周期函数--监听页面初次渲染完成
     */
    onReady: function () {
        // 页面首次渲染完毕时执行
        let height = wx.getSystemInfoSync().windowHeight
        let $navBar = this.selectComponent("#navBar")
        let navBarHeight = $navBar.data.navBarExtendHeight + $navBar.data.navBarHeight
        let viewHeight = height - navBarHeight
        this.setData({
            viewHeight: viewHeight
        })
    },

    /**
     * 生命周期函数--监听页面显示
     */
    onShow: function () {

    },

    /**
     * 生命周期函数--监听页面隐藏
     */
    onHide: function () {

    },

    /**
     * 生命周期函数--监听页面卸载
     */
    onUnload: function () {
        // this.endCaseTest()

    },

    /**
     * 页面相关事件处理函数--监听用户下拉动作
     */
    onPullDownRefresh: function () {

    },

    /**
     * 页面上拉触底事件的处理函数
     */
    onReachBottom: function () {

    },

    /**
     * 用户点击右上角分享
     */
    onShareAppMessage: function () {

    },
    /**
     * 操作日志筛选监听
     */
    onTypeChange({detail}) {
        this.setData({operationLogType: detail});
    },

    /**
     * 操作type切换
     */
    menuOneChange(e) {
        let type = e.currentTarget.dataset['index'];
        this.setData(
            {type}
        )
    },
    /**
     * 操作开关
     */
    toolShowChange(e) {
        const flag = e.currentTarget.dataset['index'] == '1' ? true : false
        const animation = wx.createAnimation({
            duration:500,
            timingFunction: 'ease',
        })
        if(flag){
            animation.height('796rpx').step()
        }else{
            animation.height('176rpx').step()
        }
        this.setData({
            animationData: animation.export()
        })
        this.setData({
            toolShow: flag
        })

    },
    endCaseTest() {
        Dialog.confirm({
            title: '是否结束练习？',
            className: 'test',
            confirmButtonText: '结束'
        }).then(async () => {
            //提交答案
            const param = {
                caseId: this.data.caseId,
                answer: this.data.operationLogList
            }
            const res = await CaseStudyTestApi.saveExamObj(param)
            wx.reLaunch({
                url: `/pages/practiceResults/practiceResults?examId=${res.data.examSelfId}&type=test`
            })
        }).catch(() => {
            // on cancel
        });
    },
    /**
     * 查询病例详情
     */
    async queryCaseDetailById() {
        const param = {
            caseId: this.data.caseId
        }
        const res = await CaseStudyTestApi.getCaseDetail(param)
        const caseData = res.data
        this.setData({
            caseData
        })
    },

    _getOperationLogNumData() {
        const operationLogList = this.data.operationLogList
        let bscjNum = 0
        let tgjcNum = 0
        let zdNumOne = 0
        let zdNumTwo = 0
        operationLogList.forEach((item, index) => {
            if (item.type == '1') {
                ++bscjNum
            } else if (item.type == '2') {
                ++tgjcNum
            } else {
                item.data.type == '1' ? ++zdNumOne : ++zdNumTwo
            }
        })
        const operationLogNumData = {
            bscjNum,
            tgjcNum,
            zdNumOne,
            zdNumTwo,
        }
        this.setData({
            operationLogNumData
        })
    },
    /**
     * 查询体格检查数接口
     */


    /**
     * 查询诊断接口
     */

    //病史采集开始==============================================
    /**
     * 查询病史采集接口
     */
    async queryCaseQuestion() {
        if(this.data.bscjData.keyWordList.length < 1){
            wx.showToast({
                title: '请添加关键词',
                icon: 'none',
                duration: 2000
            })
            return
        }
        const param = {
            caseId: this.data.caseId,
            keyWords: this.data.bscjData.keyWordList
        }
        const res = await CaseStudyTestApi.getCaseQuestion(param)
        const resultList = res.data
        if(resultList.length < 1){
            wx.showToast({
                title: '未查询到数据',
                icon: 'none',
                duration: 2000
            })
        }
        const bscjData = this.data.bscjData
        bscjData.resultList = resultList
        this.setData({
            bscjData
        })
        this._bscjResultStatusChange()
    },
    /**
     * 打开病史采集添加
     */
    openBscjAdd() {
        const bscjData = this.data.bscjData
        bscjData.addShow = true
        bscjData.keyWord = ''
        this.setData({
            bscjData
        })
    },
    bscKeyWordChange(e) {
        const keyWord = e.detail
        const bscjData = this.data.bscjData
        bscjData.keyWord = keyWord
        this.setData({
            bscjData
        })
    },
    bscjFocus(){
        this.setData({
            bscjPlaceholder:'',
            bscjId:'bscj-input'
        })
    },
    bscjBlur(){
        this.setData({
            bscjPlaceholder:'请输入关键词'
        })
    },

    onBscjAddClose() {
        const bscjData = this.data.bscjData
        bscjData.addShow = false
        this.setData({
            bscjData
        })
    },
    onBscjAddOk() {
        const keyWord = this.data.bscjData.keyWord
        if(keyWord.length < 1){
            wx.showToast({
                title: '请输入关键字',
                icon: 'none',
                duration: 2000
            })
            return
        }
        const bscjData = this.data.bscjData
        bscjData.keyWordList.push(keyWord)
        bscjData.keyWord = ''
        bscjData.focus = true
        this.setData({
            bscjData
        })
    },
    bscjAddRemove(e) {
        const index = e.currentTarget.dataset['index']
        const bscjData = this.data.bscjData
        const keyWordList = bscjData.keyWordList
        keyWordList.splice(index, 1)
        bscjData.keyWordList = keyWordList
        this.setData({
            bscjData
        })
    },
    addBscjItemClick(e) {
        const obj = e.currentTarget.dataset['obj']
        if (obj.checked) {
            return
        }
        if (this.data.operationLogNumData.bscjNum >= this.data.caseData.historyMax) {
            wx.showToast({
                title: '当前类型已超出最大上限！',
                icon: 'none',
                duration: 2000
            })
            return
        }
        const operationLogList = this.data.operationLogList
        const data = {
            type: '1',
            id: obj.id,
            time: parseTime(new Date(), '{h}:{i}'),
            data: obj
        }
        operationLogList.unshift(data)
        this.setData({
            operationLogList
        })
        this._bscjResultStatusChange()
        this._getOperationLogNumData()
    },
    /**
     * 病史采集查询结果选中
     */
    _bscjResultStatusChange() {
        const newArrId = []
        const operationLogList = this.data.operationLogList
        operationLogList.forEach(item => {
            if (item.type == 1) {
                newArrId.push(item.id)
            }
        })
        const bscjData = this.data.bscjData
        const resultList = bscjData.resultList
        resultList.forEach(item => {
            item.checked = newArrId.includes(item.id)
        })
        bscjData.resultList = resultList
        this.setData({
            bscjData
        })
    },
    //病史采集结束==============================================
    //体格检查开始==============================================
    /**
     * 查询体格检查树
     */
    async queryCaseBodyCheck() {
        const res = await CaseStudyTestApi.getCaseBodyCheck({caseId:this.data.caseId})
        const treeData = res.data
        const tgjcData = this.data.tgjcData
        tgjcData.treeData = treeData
        this.setData({
            tgjcData
        })
        this._tgjcTreeStatusChange()
    },
    /**
     * 关键字体格检查清空
     */
    clearBodyCheckKeyword(){
        this.queryCaseBodyCheck()
    },
    /**
     * 关键字查询体格检查
     */
    async queryBodyCheckKeywordLike() {
        if (this.data.tgjcData.keyWord.length < 1) {
            this.queryCaseBodyCheck()
        } else {
            const param = {
                caseId: this.data.caseId,
                keyword: this.data.tgjcData.keyWord
            }
            const res = await CaseStudyTestApi.getBodyCheckKeywordLike(param)
            const treeData = res.data
            if(treeData == null){
                wx.showToast({
                    title: '未搜索到结果',
                    icon: 'none',
                    duration: 2000
                })
            }
            const tgjcData = this.data.tgjcData
            tgjcData.treeData = treeData
            this.setData({
                tgjcData
            })
            this._tgjcTreeStatusChange()
        }
    },
    tgjcKeyWordChange(e) {
        const keyWord = e.detail
        const tgjcData = this.data.tgjcData
        tgjcData.keyWord = keyWord
        this.setData({
            tgjcData
        })
    },
    /**
     * 体格检查树一级菜单点击事件
     */
    tgcjTreeMenuClick(e) {
        const index = e.currentTarget.dataset['index']
        const tgjcData = this.data.tgjcData
        tgjcData.treeMenuIndex = index
        this.setData({
            tgjcData
        })
    },
    /**
     * 体格检查树点击最子级事件
     */
    async addTgjcItemClick(e) {
        const index = e.currentTarget.dataset['index']
        const obj = e.currentTarget.dataset['obj']
        if (obj.checked) {
            return
        }
        if (this.data.operationLogNumData.tgjcNum >= this.data.caseData.checkMax) {
            wx.showToast({
                title: '当前类型已超出最大上限！',
                icon: 'none',
                duration: 2000
            })
            return
        }
        //调用接口查询体格检查答案
        const param = {
            caseId: this.data.caseId,
            spCheckItemId: obj.id
        }
        const res = await CaseStudyTestApi.getCaseBodyCheckContent(param)
        const objItem = res.data
        //判断type等于 1、直接显示2.资料解读3.模型（直接显示）
        //判断是否开启解读
        const interpretation = this.data.caseData.interpretation
        if (objItem.type == 2  && interpretation) {
            //打开model
            const tgjcData = this.data.tgjcData
            tgjcData.name = objItem.name
            tgjcData.id = obj.id
            objItem.options.forEach(item => {
                item.key = String.fromCharCode(65 + item.isIndex)
            })
            tgjcData.options = objItem.options
            tgjcData.bodyStr = JSON.parse(objItem.bodyStr)
            tgjcData.oneItem = objItem
            tgjcData.radio = -1
            tgjcData.resultFlag = false
            this.setData({
                tgjcData,
                interpretationModel: true
            })

        }else if(objItem.type == 3 && objItem.checkSound == 3){
            //打开听诊model
            const tgjcData = this.data.tgjcData
            tgjcData.name = objItem.name
            tgjcData.id = obj.id
            objItem.options.forEach(item => {
                item.key = String.fromCharCode(65 + item.isIndex)
            })
            tgjcData.options = objItem.options
            tgjcData.oneItem = objItem
            tgjcData.radio = -1
            tgjcData.resultFlag = false
            tgjcData.interpretation = interpretation
            this.setData({
                tgjcData
            })
            await this.getBodyCheckSound(obj)
        }else {
            // objItem.id = obj.id
            const operationLogList = this.data.operationLogList
            const data = {
                type: '2',
                id: obj.id,
                time: parseTime(new Date(), '{h}:{i}'),
                data: objItem
            }
            operationLogList.unshift(data)
            this.setData({
                operationLogList
            })
            this._tgjcTreeStatusChange()
            this._getOperationLogNumData()
        }
        console.log(this.data.tgjcData)
    },
    /**
     * 体格检查选项确认
     */
    tgjcOptionEnter(val) {
        const index = val.detail.radio
        //获取数据
        const tgjcData = this.data.tgjcData
        tgjcData.radio = index
        const objItem = tgjcData.oneItem
        if(objItem.type ==3 && objItem.checkSound == 3){
            if(tgjcData.name == '心音' || tgjcData.name == '呼吸音' || tgjcData.name == '肠鸣音'){
                objItem.radioText = `${tgjcData.options[index].key}.${tgjcData.options[index].option}`
                objItem.radio = index
            }
        }else {
            objItem.radioText = `${tgjcData.options[index].key}.${tgjcData.options[index].option}`
            objItem.radio = index
        }

        objItem.optionList = val.detail.optionList
        const operationLogList = this.data.operationLogList
        let data = {
            type: '2',
            id: tgjcData.id,
            time: parseTime(new Date(), '{h}:{i}'),
            data: objItem
        }
        let  flag = -1
        operationLogList.forEach((item,i) => {
            flag = item.id == tgjcData.id?i:flag
        })
        if(flag == -1){
            operationLogList.unshift(data)
        }else {
            operationLogList[flag].data = objItem
        }
        this.setData({
            operationLogList,
            interpretationModel: false,
            soundModel:false
        })
        this._tgjcTreeStatusChange()
        this._getOperationLogNumData()
    },
    /**
     * 体格检查选项取消
     */
    tgjcOptionClose() {
        this.setData({
            interpretationModel: false,
            soundModel:false
        })
    },
    /**
     * 强制解读
     */
    constraintUnscramble(e) {
        //获取当前对象信息
        const obj = e.currentTarget.dataset['obj']
        //打开model
        const tgjcData = this.data.tgjcData
        const objItem = obj.data
        tgjcData.name = objItem.name
        tgjcData.id = obj.id
        objItem.options.forEach(item => {
            item.key = String.fromCharCode(65 + item.isIndex)
        })
        tgjcData.options = objItem.options
        tgjcData.bodyStr = JSON.parse(objItem.bodyStr)
        tgjcData.radio = Number(objItem.radio)
        tgjcData.oneItem = objItem
        debugger
        //判断作答还是查看
        const caseData = this.data.caseData
        if (caseData.interpretationUpdate) {
            tgjcData.resultFlag = false
        } else {
            tgjcData.resultFlag = true
        }
        //判断 是 选项还是听诊
        if(obj.data.type ==2){
            this.setData({
                tgjcData,
                interpretationModel: true
            })
        }else if(obj.data.type ==3 && obj.data.checkSound == 3){
            this.data.tgjcData.showPoint = obj.data.optionList
            this.setData({
                tgjcData,
                soundModel: true
            })
        }
    },
    /**
     * 查询听诊
     */
    async getBodyCheckSound(obj){
        const param = {
            caseId: this.data.caseId,
            bodyCheckId: obj.id
        }
        const res = await CaseStudyTestApi.getBodyCheckSound(param)
        const showPoint= res.data.map(item=>{
            return {
                name:item.tagName,
                url:item.url,
                x:'',
                y:'',
                image:''
            }
        })
        const tgjcData = this.data.tgjcData
        tgjcData.showPoint = showPoint
        tgjcData.showPoint = showPoint
        this.setData({
            tgjcData,
            soundModel:true
        })
    },


    /**
     * 体格检查树结果选中
     */
    _tgjcTreeStatusChange() {
        const newArrId = []
        const operationLogList = this.data.operationLogList
        operationLogList.forEach(item => {
            if (item.type == 2) {
                newArrId.push(item.id)
            }
        })
        const tgjcData = this.data.tgjcData
        const treeData = tgjcData.treeData
        treeData.forEach(item => {
            item.children.forEach(itemTwo => {
                itemTwo.children.forEach(itemThree => {
                    itemThree.checked = newArrId.includes(itemThree.id)
                })
            })
        })
        tgjcData.treeData = treeData
        this.setData({
            tgjcData
        })
    },
    //体格检查结束==============================================
    //诊断开始==============================================
    /**
     * 查询诊断
     */
    async queryCaseDiagnose() {
        if(this.data.zdData.keyWord.length < 1){
            wx.showToast({
                title: '请输入关键字！',
                icon: 'none',
                duration: 2000
            })
            return
        }
        const param = {
            caseId: this.data.caseId,
            keyword: this.data.zdData.keyWord
        }
        const res = await CaseStudyTestApi.getCaseDiagnose(param)
        const resultList = res.data
        if(resultList.length < 1){
            wx.showToast({
                title: '未搜索到结果',
                icon: 'none',
                duration: 2000
            })
        }
        const zdData = this.data.zdData
        zdData.resultList = resultList
        this.setData({
            zdData
        })
        this._zdResultStatusChange()

    },
    zdKeyWordChange(e) {
        const keyWord = e.detail
        const zdData = this.data.zdData
        zdData.keyWord = keyWord
        this.setData({
            zdData
        })
    },
    /**
     * 点击诊断搜索想
     */
    addZdItemClick(e) {
        const obj = e.currentTarget.dataset['obj']
        if (obj.checked) {
            return
        }
        if (this.data.operationLogNumData.zdNumOne >= this.data.caseData.initialDiagnose && this.data.operationLogNumData.zdNumTwo >= this.data.caseData.identificationDiagnose) {
            wx.showToast({
                title: '当前类型已超出最大上限！',
                icon: 'none',
                duration: 2000
            })
            return
        }
        if (this.data.operationLogNumData.zdNumOne >= this.data.caseData.initialDiagnose) {
            obj.type = '2'
        }
        if (this.data.operationLogNumData.zdNumTwo >= this.data.caseData.identificationDiagnose) {
            obj.type = '1'
        }

        const operationLogList = this.data.operationLogList
        const data = {
            type: '3',
            id: obj.id,
            time: parseTime(new Date(), '{h}:{i}'),
            data: obj
        }
        operationLogList.unshift(data)
        this.setData({
            operationLogList
        })
        this._zdResultStatusChange()
        this._getOperationLogNumData()
    },
    /**
     * 诊断状态修改
     */
    _zdResultStatusChange() {
        const newArrId = []
        const operationLogList = this.data.operationLogList
        operationLogList.forEach(item => {
            if (item.type == 3) {
                newArrId.push(item.id)
            }
        })
        const zdData = this.data.zdData
        const resultList = zdData.resultList
        resultList.forEach(item => {
            item.checked = newArrId.includes(item.id)
        })
        zdData.resultList = resultList
        this.setData({
            zdData
        })
        console.log(JSON.stringify(operationLogList))
    },
    /**
     * 删除诊断操作日志
     */
    lgZdItemRemove(e) {
        const index = e.currentTarget.dataset['index']
        const operationLogList = this.data.operationLogList
        operationLogList.splice(index, 1)
        this.setData({
            operationLogList
        })
        this.queryCaseDiagnose()
        this._getOperationLogNumData()
    },
    /**
     * 修改诊断操作日志状态
     */
    lgZdRadioItemChange(e) {
        const type = e.currentTarget.dataset['type']
        const index = e.currentTarget.dataset['index']
        if (type == 1 && this.data.operationLogNumData.zdNumOne >= this.data.caseData.initialDiagnose) {
            wx.showToast({
                title: '当前类型已超出最大上限！',
                icon: 'none',
                duration: 2000
            })
            return
        }
        if (type == 2 && this.data.operationLogNumData.zdNumTwo >= this.data.caseData.identificationDiagnose) {
            wx.showToast({
                title: '当前类型已超出最大上限！',
                icon: 'none',
                duration: 2000
            })
            return
        }
        const operationLogList = this.data.operationLogList
        operationLogList[index].data.type = type
        this.setData({
            operationLogList
        })
        this._getOperationLogNumData()
    },
    /**
     * 点击日志区域
     */
    loggerClick(){
        const animation = wx.createAnimation({
            duration:500,
            timingFunction: 'ease',
        })
        animation.height('176rpx').step()
        this.setData({
            toolShow:false,
            animationData: animation.export()
        })
    }
})
